package day5;

import java.util.Arrays;

//二分查找
public class Demo4 {
    public static void main(String[] args) {
        int nums[]={10,20,30,40,50,60,70};
        int number=50;
        int index=search(nums,number);
        if (index==-1){
            System.out.println("没有查到该元素！");
        }else {
            System.out.println("查到了该元素，下标："+index);
        }
        //Arrays工具类已经提供了二分查找的方法
        //Arrays.binarySearch();
    }
    public static int search(int nums[],int number){
        int min=0;
        int max= nums.length-1;

        while (min<=max) {
            int middle=(min+max)/2;
            if (number>nums[middle]){
                min=middle+1;
            }else if (number<nums[middle]) {
                max=middle-1;
            }else {
                return middle;
            }
        }

      return -1;
    }
}
